package com.paishen.peiniwan.module.login;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.paishen.common.dialog.LoadingDialog;
import com.paishen.common.util.BaseUtil;
import com.paishen.common.util.SpfsUtil;
import com.paishen.peiniwan.ActivityCollector;
import com.paishen.peiniwan.App;
import com.paishen.peiniwan.BaseActivity;
import com.paishen.peiniwan.C;
import com.paishen.peiniwan.R;
import com.paishen.peiniwan.database.UserDao;
import com.paishen.peiniwan.database.util.ModelConverter;
import com.paishen.peiniwan.frame.PnwOkCallbackAdapter;
import com.paishen.peiniwan.frame.http.PnwHttpManager;
import com.paishen.peiniwan.frame.http.entity.ServiceInfo;
import com.paishen.peiniwan.frame.http.entity.User;
import com.paishen.peiniwan.frame.http.response.HttpRespData;
import com.paishen.peiniwan.frame.http.response.HttpRespUser;
import com.paishen.peiniwan.module.MainActivity;
import com.squareup.okhttp.Request;
import com.umeng.analytics.MobclickAgent;

public class LoginLayout extends LinearLayout {
    private final AmazingBgView viewAbg;
    private ImageView imgBack, imgLogin, imgRegister, imgIcon, imgClearPhone, imgClearPwd, imgPwd, imgPhone;
    private View layPhone, layPwd, layLWrapper, viewLL1, viewLL2;
    private TextView txForget, txRTitle, txLTitle;
    private EditText edPhone, edPwd;

    private int dip100;

    final static int STEP_COVER = 1;
    final static int STEP_LOGIN = 2;

    private int currStep = STEP_COVER;
    private int lastStep = currStep;
    private boolean anim = false;

    private ValueAnimator animCover2Login, animLogin2Cover;

    public LoginLayout(Context context) {
        this(context, null);
    }


    public ImageView setOnRegisterClickListener(View.OnClickListener onRegisterClickListener) {
        if (imgRegister != null) {
            imgRegister.setOnClickListener(onRegisterClickListener);
            return imgRegister;
        }
        return null;
    }


    public LoginLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.layout_amazing_login, this);
        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // interrupt click event
                BaseUtil.hideSoftInputFromWindowAlways((Activity) getContext());
            }
        });

        dip100 = (int) (100 * context.getResources().getDisplayMetrics().density + 0.5f);

        viewAbg = (AmazingBgView) findViewById(R.id.view_abg);
        imgBack = (ImageView) findViewById(R.id.img_back);
        FrameLayout.LayoutParams lpBack = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lpBack.setMargins(dip100 / 10, dip100 / 10 + (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ? BaseUtil.getStatusBarHeight() : 0), dip100 / 10, dip100 / 10);
        imgBack.setLayoutParams(lpBack);

        imgIcon = (ImageView) findViewById(R.id.img_icon);
        imgLogin = (ImageView) findViewById(R.id.img_login);
        txLTitle = (TextView) findViewById(R.id.tx_l_title);
        layLWrapper = findViewById(R.id.lay_l_wrapper);
        viewLL1 = findViewById(R.id.view_login_line_1);
        viewLL2 = findViewById(R.id.view_login_line_2);
        imgRegister = (ImageView) findViewById(R.id.img_register);
        txRTitle = (TextView) findViewById(R.id.tx_r_title);
        layPhone = findViewById(R.id.lay_phone);
        imgPhone = (ImageView) findViewById(R.id.img_phone);
        layPwd = findViewById(R.id.lay_password);
        imgPwd = (ImageView) findViewById(R.id.img_password);
        txForget = (TextView) findViewById(R.id.tx_forget);
        edPhone = (EditText) findViewById(R.id.ed_phone);
        imgClearPhone = (ImageView) findViewById(R.id.img_clear_phone);
        imgClearPwd = (ImageView) findViewById(R.id.img_clear_pwd);
        edPwd = (EditText) findViewById(R.id.ed_pwd);

        refreshUIByCurrState();

        imgLogin.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currStep == STEP_COVER) {
                    currStep = STEP_LOGIN;
                    refreshUIByCurrState();
                } else if (currStep == STEP_LOGIN) {
                    boolean result = edPhone.getText().length() == 11 && edPwd.getText().length() >= 6;
                    if (!result) {
                        BaseUtil.showToast(R.string.login_fail);
                        return;
                    }

                    requestLogin(edPhone.getText().toString(), edPwd.getText().toString());
                }
            }
        });

        imgClearPhone.setVisibility(View.INVISIBLE);
        imgClearPhone.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                edPhone.setText("");
            }
        });
        imgClearPwd.setVisibility(View.INVISIBLE);
        imgClearPwd.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                edPwd.setText("");
            }
        });


        imgBack.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currStep == STEP_LOGIN) {
                    currStep = STEP_COVER;
                    refreshUIByCurrState();
                    BaseUtil.hideSoftInputFromWindowAlways((Activity) getContext());
                }
            }
        });

        edPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                imgClearPhone.setVisibility(edPhone.getText().length() > 0 ? View.VISIBLE : View.GONE);
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        edPhone.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                layPhone.setBackgroundResource(hasFocus ? R.drawable.login_selector_edit_input_focus : R.drawable.login_selector_edit_input_normal);
                imgPhone.setImageResource(hasFocus ? R.mipmap.edit_phone_amazing_focus : R.mipmap.edit_phone_amazing_normal);
                if (!hasFocus) {
                    imgClearPhone.setVisibility(View.GONE);
                } else {
                    if (edPhone.getText().length() > 0) imgClearPhone.setVisibility(View.VISIBLE);
                }
            }
        });
        edPwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                imgClearPwd.setVisibility(edPhone.getText().length() > 0 ? View.VISIBLE : View.GONE);
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        edPwd.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                layPwd.setBackgroundResource(hasFocus ? R.drawable.login_selector_edit_input_focus : R.drawable.login_selector_edit_input_normal);
                imgPwd.setImageResource(hasFocus ? R.mipmap.edit_lock_amazing_focus : R.mipmap.edit_lock_amazing_normal);
                if (!hasFocus) {
                    imgClearPwd.setVisibility(View.GONE);
                } else {
                    if (edPwd.getText().length() > 0) imgClearPwd.setVisibility(View.VISIBLE);
                }
            }
        });

        txForget.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(v.getContext(), RegisterAuthActivity.class);
                intent.putExtra(RegisterAuthActivity.EXTRA_AUTH_TITLE, v.getContext().getString(R.string.register_pwd_forget));
                v.getContext().startActivity(intent);
            }
        });
    }

    public void intoLoginMode() {
        currStep = STEP_LOGIN;
        lastStep = currStep;
        refreshUIByCurrState();

        if (App.i().getUser() != null) edPhone.setText(App.i().getUser().getPhone());
    }


    private void refreshUIByCurrState() {
        if (currStep == STEP_COVER && lastStep == STEP_COVER) {
            imgBack.setVisibility(View.GONE);
            layPhone.setVisibility(View.GONE);
            viewLL1.setVisibility(View.GONE);
            viewLL2.setVisibility(View.GONE);
            layPwd.setVisibility(View.GONE);
            txForget.setVisibility(View.GONE);
            imgLogin.setVisibility(View.VISIBLE);
            imgRegister.setVisibility(View.VISIBLE);
            imgIcon.setVisibility(View.VISIBLE);
            edPhone.setEnabled(false);
            edPwd.setEnabled(false);
        } else if (currStep == STEP_LOGIN && lastStep == STEP_LOGIN) {
            imgBack.setVisibility(View.VISIBLE);
            layPhone.setVisibility(View.VISIBLE);
            layPwd.setVisibility(View.VISIBLE);
            txForget.setVisibility(View.VISIBLE);
            layLWrapper.setTranslationY(dip100 * 1.5f);
            viewLL1.setVisibility(View.VISIBLE);
            viewLL2.setVisibility(View.VISIBLE);
            imgLogin.setVisibility(View.VISIBLE);
            imgRegister.setVisibility(View.GONE);
            imgIcon.setVisibility(View.GONE);
            txLTitle.setAlpha(0f);
            txRTitle.setAlpha(0f);
            edPhone.setEnabled(true);
            edPwd.setEnabled(true);
        } else if (currStep == STEP_LOGIN && lastStep == STEP_COVER) {
            if (!anim) {
                animCover2Login = ValueAnimator.ofFloat(0, 1).setDuration(600);
                animCover2Login.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                    @Override
                    public void onAnimationUpdate(ValueAnimator animation) {
                        float fraction = animation.getAnimatedFraction();
                        if (fraction >= 0 && fraction < 0.5f) {
                            float p1 = fraction / 0.5f;
                            imgIcon.setTranslationY(-dip100 * p1);
                            imgIcon.setAlpha(1 - p1);
                            imgRegister.setScaleX(1 - p1);
                            imgRegister.setScaleY(1 - p1);
                            layLWrapper.setTranslationY(dip100 * 1.5f * p1);
                            txRTitle.setAlpha(1 - p1);
                            txLTitle.setAlpha(1 - p1);
                        } else if (fraction <= 1f) {
                            imgIcon.setTranslationY(-dip100);
                            imgIcon.setAlpha(0f);
                            imgRegister.setScaleX(0);
                            imgRegister.setScaleY(0);
                            imgRegister.setVisibility(View.GONE);
                            layLWrapper.setTranslationY(dip100 * 1.5f);
                            txRTitle.setAlpha(0);
                            txLTitle.setAlpha(0);
                            viewLL1.setVisibility(View.VISIBLE);
                            viewLL2.setVisibility(View.VISIBLE);

                            float p2 = (fraction - 0.5f) / 0.5f;
                            imgBack.setAlpha(p2);


                            layPhone.setTranslationX(dip100 * 1.5f * (1 - p2));
                            layPhone.setAlpha(p2);
                            layPwd.setTranslationX(-dip100 * 1.5f * (1 - p2));
                            layPwd.setAlpha(p2);
                            txForget.setTranslationX(dip100 * 1.5f * (1 - p2));
                            txForget.setAlpha(p2);

                            viewLL1.setPivotX(viewLL1.getWidth());
                            viewLL1.setScaleX(p2);
                            viewLL2.setPivotX(0);
                            viewLL2.setScaleX(p2);
                        }
                    }
                });
                animCover2Login.addListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationStart(Animator animation) {
                        super.onAnimationStart(animation);
                        imgLogin.setEnabled(false);
                        imgRegister.setEnabled(false);

                        imgBack.setVisibility(View.VISIBLE);
                        imgBack.setAlpha(0f);
                        imgBack.setEnabled(false);
                        layPhone.setVisibility(View.VISIBLE);
                        layPhone.setAlpha(0f);
                        layPwd.setVisibility(View.VISIBLE);
                        layPwd.setAlpha(0f);
                        txForget.setVisibility(View.VISIBLE);
                        txForget.setAlpha(0f);
                        txForget.setEnabled(false);

                        edPhone.setEnabled(false);
                        edPwd.setEnabled(false);
                    }

                    @Override
                    public void onAnimationEnd(Animator animation) {
                        super.onAnimationEnd(animation);
                        imgLogin.setEnabled(true);
                        imgBack.setAlpha(1f);
                        imgBack.setEnabled(true);
                        layPhone.setAlpha(1f);
                        layPhone.setTranslationY(0);
                        layPwd.setAlpha(1f);
                        layPwd.setTranslationY(0);
                        txForget.setAlpha(1f);
                        txForget.setEnabled(true);
                        viewLL1.setScaleX(1);
                        viewLL2.setScaleX(1);

                        edPhone.setEnabled(true);
                        edPwd.setEnabled(true);

                        lastStep = STEP_LOGIN;
                        anim = false;
                    }
                });
                animCover2Login.start();
                anim = true;
            }
        } else if (currStep == STEP_COVER && lastStep == STEP_LOGIN) {
            if (!anim) {
                animLogin2Cover = ValueAnimator.ofFloat(0, 1).setDuration(400);
                animLogin2Cover.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                    @Override
                    public void onAnimationUpdate(ValueAnimator animation) {
                        float fraction = animation.getAnimatedFraction();

                        if (fraction >= 0 && fraction < 0.6f) {
                            float p1 = fraction / 0.6f;

                            imgBack.setAlpha(1 - p1);

                            layPhone.setTranslationX(dip100 * 1.5f * p1);
                            layPhone.setAlpha(1 - p1);
                            layPwd.setTranslationX(-dip100 * 1.5f * p1);
                            layPwd.setAlpha(1 - p1);
                            txForget.setTranslationX(dip100 * 1.5f * p1);
                            txForget.setAlpha(1 - p1);

                            viewLL1.setPivotX(0);
                            viewLL1.setScaleX(1 - p1);
                            viewLL2.setPivotX(viewLL2.getWidth());
                            viewLL2.setScaleX(1 - p1);

                        } else if (fraction <= 1f) {
                            imgBack.setAlpha(0f);

                            layPhone.setAlpha(0f);
                            layPhone.setTranslationX(0);
                            viewLL1.setScaleX(0);
                            viewLL2.setScaleX(0);
                            layPwd.setAlpha(0f);
                            layPwd.setTranslationX(0);
                            txForget.setAlpha(0f);
                            txForget.setTranslationX(0);


                            float p2 = (fraction - 0.6f) / 0.4f;

                            imgIcon.setVisibility(View.VISIBLE);
                            imgIcon.setAlpha(p2);
                            imgIcon.setTranslationY(-dip100 * (1 - p2));

                            layLWrapper.setTranslationY(dip100 * (1.5f * (1 - p2)));
                            txRTitle.setAlpha(p2);
                            txLTitle.setAlpha(p2);

                            imgRegister.setVisibility(View.VISIBLE);
                            imgRegister.setScaleX(p2);
                            imgRegister.setScaleY(p2);

                        }
                    }
                });
                animLogin2Cover.addListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationStart(Animator animation) {
                        super.onAnimationStart(animation);
                        imgBack.setEnabled(false);
                        imgLogin.setEnabled(false);
                        txForget.setEnabled(false);
                        edPhone.setEnabled(false);
                        edPwd.setEnabled(false);
                    }

                    @Override
                    public void onAnimationEnd(Animator animation) {
                        super.onAnimationEnd(animation);
                        imgLogin.setEnabled(true);
                        imgRegister.setEnabled(true);

                        imgIcon.setAlpha(1f);
                        imgLogin.setAlpha(1f);
                        imgRegister.setAlpha(1f);
                        imgRegister.setScaleX(1f);
                        imgRegister.setScaleY(1f);

                        layLWrapper.setTranslationY(0);
                        txRTitle.setAlpha(1f);
                        txLTitle.setAlpha(1f);

                        lastStep = STEP_COVER;
                        anim = false;
                    }
                });
                animLogin2Cover.start();
                anim = true;
            }

        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (animCover2Login != null) {
            animCover2Login.cancel();
            animCover2Login = null;
        }

        if (animLogin2Cover != null) {
            animLogin2Cover.cancel();
            animLogin2Cover = null;
        }
    }

    public boolean dealBackPressed() {
        if (anim) {
            return true;
        }
        if (currStep == STEP_LOGIN) {
            imgBack.performClick();
            return true;
        }
        return false;
    }

    private void requestLogin(final String phone, final String password) {
        final LoadingDialog dlgLoading = new LoadingDialog.Builder(getContext()).setCanCancel(false).create();
        dlgLoading.show();

        String platform = "paishen";
        try {
            ApplicationInfo appInfo = getContext().getPackageManager().getApplicationInfo(getContext().getPackageName(),
                    PackageManager.GET_META_DATA);
            platform = appInfo.metaData.getString("UMENG_CHANNEL");
        } catch (PackageManager.NameNotFoundException ignored) {
        }

        PnwHttpManager.Token.getServer(((BaseActivity) getContext()).TAG, BaseUtil.getAppVersionCode(), platform, new PnwOkCallbackAdapter<HttpRespData<ServiceInfo>>() {
            @Override
            public void onResponse(HttpRespData<com.paishen.peiniwan.frame.http.entity.ServiceInfo> response, boolean fresh) {
                super.onResponse(response, fresh);
                if (response.errcode == C.http.RESULT_SUCCESS) {
                    PnwHttpManager.setCurrServiceUrl(response.data.server);

                    PnwHttpManager.User.login(((BaseActivity) getContext()).TAG, phone, password, new PnwOkCallbackAdapter<HttpRespUser<User>>() {
                                @Override
                                public void onResponse(HttpRespUser<User> response, boolean fresh) {
                                    super.onResponse(response, fresh);
                                    dlgLoading.dismiss();
                                    if (response.errcode == C.http.RESULT_SUCCESS) {
                                        SpfsUtil.write(C.sp.CURRENT_LOGIN_USER_ID, response.user.id);
                                        final UserDao userDao = App.i().getDaoSession(response.user.id).getUserDao();
                                        com.paishen.peiniwan.database.User dbUser = userDao.queryBuilder().where(UserDao.Properties.Id.eq(response.user.id)).unique();
                                        dbUser = ModelConverter.mergeOrReplace(dbUser, response.user);
                                        dbUser.setPhone(phone);
                                        dbUser.setPassword(password);
                                        dbUser.setApp_auto_login(true);
                                        App.i().setUser(dbUser);
                                        userDao.insertOrReplace(dbUser);

                                        // 在App.i().setUser() 后，设置最后一次位置信息
                                        App.i().locationAsync();

                                        MobclickAgent.onProfileSignIn(phone);

                                        Intent intent = new Intent(getContext(), MainActivity.class);
                                        getContext().startActivity(intent);
                                        ActivityCollector.finishAllExcept(MainActivity.class);
                                    } else if (fresh && response.errcode != C.http.RESULT_LOGIN_EXPIRE &&
                                            response.errcode != C.http.RESULT_LOGIN_OFFLINE) {
                                        BaseUtil.showToast(response.errmsg);
                                    }
                                }

                                @Override
                                public void onFailure(Request request, Exception e) {
                                    super.onFailure(request, e);
                                    dlgLoading.dismiss();
                                }
                            }
                    );
                } else {
                    BaseUtil.showToast(response.errmsg);
                }
            }

            @Override
            public void onFailure(Request request, Exception e) {
                super.onFailure(request, e);
                dlgLoading.dismiss();
            }
        });
    }

    public AmazingBgView getAmazingBgView() {
        return viewAbg;
    }

}
